<?php
declare(strict_types=1);

namespace app\api\logic;

use app\admin\logic\system\SystemConfigLogic;
use app\basic\BaseLogic;
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
use support\utils\Arr;

class EmailLogic extends BaseLogic
{
    protected $userDocLogic;
    protected $articleLogic;

    private $error;

    public function __construct()
    {
        $this->userDocLogic = new UserDocLogic();
        $this->articleLogic = new ArticleLogic();
    }

    /**
     * 发送文档邮件
     * @param int $userId 用户ID
     * @param int $docId 文档ID
     * @param string $email 接收邮箱
     * @return bool
     */
    public function sendDocEmail($userId, $docId, $email)
    {
        try {
            // 验证邮箱格式
            if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
                return $this->setError('邮箱格式不正确');
            }

            // 检查用户是否已购买该文档
            if (!$this->userDocLogic->checkUserBought($userId, $docId)) {
                return $this->setError('您尚未购买该文档');
            }

            // 获取文档信息
            $docInfo = $this->articleLogic->where('id', $docId)->find();

            if (empty($docInfo)) {
                 $this->setError('文档不存在');
                 return false;
            }

              // 检查文档URL
            if (empty($docInfo['filepath'])) {
                 $this->setError('文档文件不存在');
                 return false;
            }

            // 创建临时文件目录
            $tempDir = runtime_path() . '/temp/';
            if (!is_dir($tempDir)) {
                mkdir($tempDir, 0777, true);
            }

              // 生成临时文件名
            $tempFile = $tempDir . uniqid() . '.' . $docInfo['fileext'];

             // 下载文件
            try {
                // 设置文件下载超时时间
                $ctx = stream_context_create([
                    'http' => [
                        'timeout' => 30 // 设置30秒超时
                    ]
                ]);

                // 获取文件内容
                $fileContent = file_get_contents($docInfo['filepath'], false, $ctx);
                if ($fileContent === false) {
                    return $this->setError('文档下载失败');
                }

                // 保存到临时文件
                if (file_put_contents($tempFile, $fileContent) === false) {
                    return $this->setError('临时文件创建失败');
                }

                // 验证文件是否成功下载
                if (!file_exists($tempFile) || filesize($tempFile) == 0) {
                    return $this->setError('文件下载不完整');
                }
            } catch (\Exception $e) {
                // 清理临时文件
                @unlink($tempFile);
                return $this->setError('文档下载失败：' . $e->getMessage());
            }

            // 发送邮件
            $mail = new PHPMailer(true);

            try {
                $logic = new SystemConfigLogic();
                $config = $logic->getGroup('email_config');
                // 邮件服务器配置
                $mail->SMTPDebug = intval(Arr::getConfigValue($config,'SMTPDebug'));
                $mail->isSMTP();
                $mail->Host = Arr::getConfigValue($config,'Host');
                $mail->SMTPAuth = true;
                $mail->Username = Arr::getConfigValue($config,'Username');
                $mail->Password = Arr::getConfigValue($config,'Password');
                $mail->SMTPSecure = Arr::getConfigValue($config,'SMTPSecure');
                $mail->Port = Arr::getConfigValue($config,'Port');
                $mail->CharSet = Arr::getConfigValue($config,'CharSet');

                // 发件人
                $mail->setFrom(Arr::getConfigValue($config,'From'), Arr::getConfigValue($config,'FromName'));

                // 收件人
                $mail->addAddress($email);

                // 邮件内容
                $mail->isHTML(true);
                $mail->Subject = '您购买的文档：' . $docInfo['title'];
                $mail->Body = "
                    <p>您好！</p>
                    <p>这是您购买的文档：{$docInfo['title']}</p>
                    <p>文档已作为附件发送，请查收。</p>
                    <p>如有问题，请联系客服。</p>
                ";
                // 添加附件
                $mail->addAttachment($tempFile, $docInfo['title'] . '.' . $docInfo['fileext']);

                // 发送
                $mail->send();


                 // 发送成功后再删除临时文件
                 @unlink($tempFile);
                return true;

            } catch (Exception $e) {
                @unlink($tempFile);
                return $this->setError('邮件发送失败：' . $mail->ErrorInfo);
            }

        } catch (\Exception $e) {
            return $this->setError($e->getMessage());
        }
    }


    public function setError($error)
    {
        $this->error = $error;
    }

    public function getError()
    {
        return $this->error;
    }
}